/** @odoo-module **/
import {formatId} from "./tool.js";

class cellEditor{
    // 创建编辑器后调用一次
    init(params){
        let _this = this;
        let is_te_pei = !!params.data.te_pei_json;
        _this.is_te_pei = is_te_pei;
        // console.log(isTese);
        this.charPress = params.charPress;
        this.charPressDish;
        if(this.IsJsonString(this.charPress) && typeof JSON.parse(this.charPress) == 'object'){
            this.charPressDish = JSON.parse(this.charPress);
            // console.log(this.charPressDish);
        }
        this.params = params;
        this.owl = params.context.owl_widget;
        this.data = params.data;
        this.field = params.colDef.field;
        this.day = params.colDef.field.split('_')[0];
        this.dish_data = [];
        this.dish = this.data[this.day+'_dish_key'];

        this.activeIndex = -1;

        let value = params.value || '';
        let disabled = !!this.charPressDish;

        this.oldValue = value;
        this.currentValue = value;
        this.old_pei_json = [];
        this.pei_json = [];
        this.te_id = '';
        if(is_te_pei){
            this.te_id = this.dish.id;
            this.pei_json = JSON.parse(JSON.stringify(this.data.te_pei_json[this.day]));
            this.old_pei_json = JSON.parse(JSON.stringify(this.data.te_pei_json[this.day]));
        }
        let el = document.createElement('div');
        el.setAttribute('style', 'position: relative;');
        let _html = '';
        _html += `<input type="text" class="form-control searchName" placeholder="请输入菜品名" value="${value}" ${disabled?'disabled':''}/>`;
        _html += `<div class="result" style="height: 329px"><ul class="list-group list-group-flush resultData"></ul><div>`
        el.innerHTML = _html;
        this.el = el;
        this.inputEl = this.el.querySelector('input');
        if(is_te_pei && !this.charPressDish){
            this.setTePeiNode();
        }
        this.bindInput();

        // el.querySelectorAll('li').forEach(function (e){
        //     e.addEventListener('click',function (){
        //         _this.bindClick(e);
        //     })
        // });

    }
    setTePeiNode(){
        let _this = this;
        let te_pei_box = this.el.querySelector('.te_pei_box');
        if(te_pei_box){
            te_pei_box.parentNode.removeChild(te_pei_box);
        }
        let currentValueArr = [];
        let el = document.createElement('div');
        el.setAttribute('class','te_pei_box');
        // el.setAttribute('style', 'position: absolute;bottom:370px;background: #ffffff;width: 100%;min-height: 32px;box-shadow: 1px 0px 4px rgba(0, 0, 0, 0.3);');
        el.setAttribute('style', 'display:flex');
         let pei_json = this.pei_json;
         let arr = [];
         if(this.te_id){
             let name = this.owl.dish_key[this.te_id].name;
             // let c_name = this.owl.dish_top_category[this.owl.dish_key[this.te_id].dish_top_category_id].name_cn;
             arr.push({
                 name:name,
                 id:this.te_id,
                 // dish_top_category_name:c_name
             })
             currentValueArr.push(name);
             this.pei_json.forEach(id=>{
                 currentValueArr.push(this.owl.formatterTePeiIdToStr(id));
                 let name = this.owl.dish_key[id].name;
                 // let c_name = this.owl.dish_top_category[this.owl.dish_key[id].dish_top_category_id].name_cn;
                 arr.push({
                     name:name,
                     id:id,
                     // dish_top_category_name:c_name
                 })
             });
         }

        this.currentValue = currentValueArr.join('/');
        let _html = '';

        arr.forEach((v,i)=>{
            _html += `<div style="padding: 5px;">`;
            _html += `<svg data-id="${v.id}" style="cursor: pointer" t="1690877303774" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3817" width="14" height="14"><path d="M597.795527 511.488347 813.564755 295.718095c23.833825-23.833825 23.833825-62.47489 0.001023-86.307691-23.832801-23.832801-62.47489-23.833825-86.307691 0L511.487835 425.180656 295.717583 209.410404c-23.833825-23.833825-62.475913-23.833825-86.307691 0-23.832801 23.832801-23.833825 62.47489 0 86.308715l215.769228 215.769228L209.410915 727.258599c-23.833825 23.833825-23.833825 62.47489 0 86.307691 23.832801 23.833825 62.473867 23.833825 86.307691 0l215.768205-215.768205 215.769228 215.769228c23.834848 23.833825 62.475913 23.832801 86.308715 0 23.833825-23.833825 23.833825-62.47489 0-86.307691L597.795527 511.488347z" fill="#dc3545" p-id="3818"></path></svg>`
            _html += `<span>${v.name}</span>`;
            _html += '</div>';
        })
        _html += '<div class="text-bg-success te_pei_btn" style="padding: 5px;cursor: pointer">【确定】</div>'

        el.innerHTML = _html;
        el.querySelectorAll('svg').forEach(function (e){
            e.addEventListener('click',function (){
                let id = formatId(e.dataset.id);
                if(id == _this.te_id){
                    _this.te_id = '';
                    _this.pei_json = [];
                }else{
                    _this.pei_json = _this.pei_json.filter(v=>v!= id);
                }
                _this.setTePeiNode();
                _this.setResult();
            })
        });
        el.querySelector('.te_pei_btn').addEventListener('click',function (){
            _this.updataAndStopEditing(_this.currentValue);
        });
        this.el.insertBefore(el,this.inputEl);
    }
    IsJsonString(str) {
        try {
            JSON.parse(str);
        } catch(e) {
            return false;
        }
        return true;
    }

    // 插入elementNode
    getGui(){
        // this.el.getElementsByClassName('searchName')[0].focus();
        // let a = this.el.querySelector('input');
        // a.focus();
        return this.el;
    }
    // 将值发送到当前的表格
    getValue(){
        return this.currentValue
    }
    // 编辑开始前调用
    isCancelBeforeStart() {
        return false;
    }
    // 编辑结束后返回一次
    // 如果返回true,编辑结果失效
    isCancelAfterEnd(){
        // console.log('oldValue',this);
        if(this.currentValue == this.oldValue){
            return true;
        }else{
            return false;
        }
    }

    afterGuiAttached(){
        if(this.charPressDish){
            this.setMenu();
        }else{
            let _str = this.charPress;
            this.inputEl.value = '';
            this.inputEl.focus();
            this.inputEl.value = _str || this.currentValue;
            if(this.is_te_pei){
                this.inputEl.value = '';
            }
            this.setResult();
        }
    }

    isPopup(){
        return true
    }

    // getPopupPosition(){
    //     return 'under'
    // }
    bindInput(){
        let _this = this;
        // let _input = el.getElementsByClassName('searchName')[0];
        let _input = this.inputEl;
        _input.onkeyup = (e) => {
            _this.setResult();
            // 按键监听
            // console.log(e.keyCode);
            // console.log(e.which);
            if(e.which === 40){
                _this.keyDown();
            }
            if(e.which === 38){
                _this.keyUp();
            }
            if(e.which === 13 && _this.activeIndex != -1){
                _this.keyEnter();
            }
        }

        _input.onkeydown = (e) => {
            if(e.which === 13 && _this.activeIndex != -1){
                e.stopPropagation();
            }
            if(e.which === 40){
                e.stopPropagation();
            }
            if(e.which === 38){
                e.stopPropagation();
            }
        };

        // _input.onchange = (e) => {
        //     _this.activeIndex = -1;
        //     _this.updataActive();
        // }
    }

    setMenu(){
        let _this = this;
        let el = this.el;
        let dish = this.charPressDish;
        // console.log(dish);
        let str = '';
        let name = dish.name;
        if(dish.te_pei_json){
            dish.te_pei_json.forEach(v=>{
                name+=('/'+_this.owl.dish_key[v].name)
            })
        }
        str += `<li class="list-group-item" data-id="copy">复制：${name}</li>`;
        str += `<li class="list-group-item" data-id="swap">与“${name}”交换</li>`;
        str += `<li class="list-group-item" data-id="cancel">取消</li>`;
        el.getElementsByTagName('ul')[0].innerHTML = str;
        el.querySelectorAll('li').forEach(function (e){
            e.addEventListener('click',function (){
                _this.bindClickCopy(e);
            })
        });
    }

    setTePeiResult(){
        let _this = this;
        let el = this.el;
        let _input = this.inputEl;
        let str = '';
        // let options = '';
        let arr = [];
        let count = 0;
        let index = this.owl.index;
        let isCreat = true;
        let day = this.day;
        let isLimitCategory = (_this.owl.state.editConfig.limitCategory === '1');
        let isLimitCost = (_this.owl.state.editConfig.limitCost === '1');
        let index_dish_key = JSON.parse(JSON.stringify(index.dish_key));
        if(_this.te_id){
            index_dish_key = index_dish_key.filter(v=>v.dish_top_category_id !=4);
        }else{
            index_dish_key = index_dish_key.filter(v=>v.dish_top_category_id == 4);
        }
        for (const dish_key of index_dish_key) {
            let dish_top_category_name = '';
            try {
                dish_top_category_name = this.owl.dish_top_category[dish_key.dish_top_category_id].name_cn;
            }catch (e){}
            let flag = (isLimitCategory &&  this.data[day+'_limit_category_id'] == dish_key.plan_top_category_id && !_this.te_id) || !isLimitCategory;
            let flag2 = (isLimitCost && dish_key.dish_cost >= this.data.minCost && dish_key.dish_cost <= this.data.maxCost && !_this.te_id) || !isLimitCost;
            if(flag && flag2 && dish_key.name.trim()!=''){
                if(count>= 7) break;
                if(_input.value.trim() != "" && dish_key.name.includes(_input.value)){
                    str += `<li class="list-group-item" data-id="${dish_key.id}" data-name="${dish_key.name}">${dish_key.name}${dish_top_category_name?'('+dish_top_category_name+')':''}(￥${dish_key.dish_cost||0})</li>`;
                    arr.push(dish_key);
                    count ++;
                }
                if(_input.value.trim() == ""){
                    str += `<li class="list-group-item" data-id="${dish_key.id}" data-name="${dish_key.name}">${dish_key.name}${dish_top_category_name?'('+dish_top_category_name+')':''}(￥${dish_key.dish_cost||0})</li>`;
                    arr.push(dish_key);
                    count ++;
                }
                if(_input.value.trim() == dish_key.name){// 判断是否需要创建菜品
                    isCreat = false;
                }
            }
        }
        // isCreat = false;
        if(!_this.te_id){
            isCreat && (str += `<li class="list-group-item liCreateBtn" data-id="create" data-name="${_input.value}">创建新特色菜品：${_input.value}</li>`);
            str += `<li class="list-group-item liMoreBtn" data-id="more">查找更多特色...</li>`;
        }
        str += `<li class="list-group-item text-danger" data-id="clear">清空</li>`;
        _this.dish_data = arr;
        el.getElementsByTagName('ul')[0].innerHTML = str;

        el.querySelectorAll('li').forEach(function (e){
            e.addEventListener('click',function (){
                _this.bindTePeiClick(e);
            })
        });

    }

    setResult(){
        if(this.is_te_pei){
            this.setTePeiResult();
            return;
        }
        let _this = this;
        let el = this.el;
        let _input = this.inputEl;
        let str = '';
        // let options = '';
        let arr = [];
        let count = 0;
        let index = this.owl.index;
        let isCreat = true;
        let day = this.day;
        let isLimitCategory = (_this.owl.state.editConfig.limitCategory === '1');
        let isLimitCost = (_this.owl.state.editConfig.limitCost === '1');

        for (const dish_key of index.dish_key) {
            let flag = (isLimitCategory &&  this.data[day+'_limit_category_id'] == dish_key.plan_top_category_id) || !isLimitCategory;
            let flag2 = (isLimitCost && dish_key.dish_cost >= this.data.minCost && dish_key.dish_cost <= this.data.maxCost) || !isLimitCost;
            if(dish_key.dish_top_category_id == this.data.dish_top_category_id && flag && flag2 && dish_key.name.trim()!=''){
                if(count>= 7) break;
                if(_input.value.trim() != "" && dish_key.name.includes(_input.value)){
                    str += `<li class="list-group-item" data-id="${dish_key.id}" data-name="${dish_key.name}">${dish_key.name}(￥${dish_key.dish_cost||0})</li>`;
                    arr.push(dish_key);
                    count ++;
                }
                if(_input.value.trim() == ""){
                    str += `<li class="list-group-item" data-id="${dish_key.id}" data-name="${dish_key.name}">${dish_key.name}(￥${dish_key.dish_cost||0})</li>`;
                    arr.push(dish_key);
                    count ++;
                }
            }
            if(_input.value.trim() == dish_key.name && dish_key.dish_top_category_id == this.data.dish_top_category_id){// 判断是否需要创建菜品
                isCreat = false;
            }
        }

        isCreat && (str += `<li class="list-group-item liCreateBtn" data-id="create" data-name="${_input.value}">创建新菜品：${_input.value}</li>`);
        str += `<li class="list-group-item liMoreBtn" data-id="more">查找更多...</li>`;
        str += `<li class="list-group-item text-danger" data-id="clear">清空</li>`;
        _this.dish_data = arr;
        el.getElementsByTagName('ul')[0].innerHTML = str;
        // el.getElementsByTagName('datalist')[0].innerHTML = options;

        el.querySelectorAll('li').forEach(function (e){
            e.addEventListener('click',function (){
                _this.bindClick(e);
            })
        });
    }

    keyUp(){
        if(this.activeIndex != -1){
            this.activeIndex--;
        }
        this.updataActive();
    }

    keyDown(){
        if(this.el.querySelectorAll('li').length == this.activeIndex+1){
            this.activeIndex = -1;
        }else{
            this.activeIndex++;
        }
        this.updataActive();
    }

    keyEnter(){
        // console.log('keyEnter');
        let _this = this;
        this.el.querySelectorAll('li').forEach(function (e,i){
            if(i == _this.activeIndex){
                if(_this.is_te_pei){
                    _this.bindTePeiClick(e);
                }else{
                    _this.bindClick(e);
                }
                _this.activeIndex = -1;
            }
        });
    }

    bindTePeiClick(e){
        let _this = this;
        let id = e.getAttribute('data-id');
        let name = e.getAttribute('data-name');
        // let dish_top_category_id = this.owl.dish_key[id].dish_top_category_id;
        let dish_top_category_id = _this.data.dish_top_category_id;
        let dish_top_category_name_cn = _this.data.dish_top_category_name_cn;
        let day = _this.day;
        let dish = this.dish;
        if(id == 'more'){
            _this.owl.showDishListModal({
                // 菜品列表筛选参数
                dish_top_category_id:dish_top_category_id,
                dish_top_category_name_cn:dish_top_category_name_cn,
                plan_top_category_id:_this.data[_this.day+'_limit_category_id']
            },(d)=>{
                this.te_id = d.id;
                this.setTePeiNode();
                this.inputEl.value = '';
                this.inputEl.focus();
                this.setResult();
                // _this.updataAndStopEditing(d.name);
            });
            return;
        }
        if(id == 'create'){
            let newDish = JSON.parse(JSON.stringify(dish));

            newDish.name = name || '';
            if(!newDish.dish_top_category_id){
                newDish.dish_top_category_id = dish_top_category_id;
            }
            newDish.plan_top_category_id = _this.data[day+'_limit_category_id'];
            _this.owl.creatDish(newDish,(d)=>{
                // console.log('---------------');
                // console.log(d);
                this.te_id = d.id;
                this.setTePeiNode();
                this.inputEl.value = '';
                this.inputEl.focus();
                this.setResult();
                // _this.updataAndStopEditing(d.name);
            });
            return;
        }
        if(id == 'clear'){
            _this.updataAndStopEditing('');
            return;
        }

        id = formatId(id);
        dish_top_category_id = this.owl.dish_key[id].dish_top_category_id;
        if(dish_top_category_id == 4){
            this.te_id = id;
        }else {
            if(!this.pei_json.includes(id)){
                this.pei_json.push(id);
            }
        }
        this.setTePeiNode();
        this.inputEl.value = '';
        this.inputEl.focus();
        this.setResult();
    }

    bindClick(e){
        // console.log('bindClick');
        // console.log(e);
        let _this = this;
        let id = e.getAttribute('data-id');
        let name = e.getAttribute('data-name');
        let dish_top_category_id = _this.data.dish_top_category_id;
        let dish_top_category_name_cn = _this.data.dish_top_category_name_cn;
        let day = _this.day;
        let dish = this.dish;
        // console.log(e.getAttribute('data-id'));
        // console.log(name);
        if(id == 'more'){
            _this.owl.showDishListModal({
                // 菜品列表筛选参数
                dish_top_category_id:dish_top_category_id,
                dish_top_category_name_cn:dish_top_category_name_cn,
                plan_top_category_id:_this.data[_this.day+'_limit_category_id']
            },(d)=>{
                _this.updataAndStopEditing(d.name);
            });
        }else if(id == 'create'){
            let newDish = JSON.parse(JSON.stringify(dish));
            // console.log(newDish);
            newDish.name = name || '';
            if(!newDish.dish_top_category_id){
                newDish.dish_top_category_id = dish_top_category_id;
            }
            newDish.plan_top_category_id = _this.data[day+'_limit_category_id'];
            _this.owl.creatDish(newDish,(d)=>{
                _this.updataAndStopEditing(d.name);
            });
        }else if(id == 'clear'){
            _this.updataAndStopEditing('');
        }else if (id){
            _this.updataAndStopEditing(name);
        }
    }

    bindClickCopy(e){
        let _this = this;
        let id = e.getAttribute('data-id');
        let charPressDish = this.charPressDish;
        // let dish_top_category_id = _this.data.dish_top_category_id;
        let copyValue = charPressDish.name;
        if(charPressDish.te_pei_json){
            charPressDish.te_pei_json.forEach(id=>{
                copyValue += ('/'+_this.owl.formatterTePeiIdToStr(id));
            })
        }
        if(id == 'copy'){
            _this.updataAndStopEditing(copyValue);
        }else if(id == 'swap'){
            _this.updataAndStopEditing(copyValue);
            // 拖动的那一格更新
            let rowNode = this.params.api.getRowNode(charPressDish.from.id);
            rowNode.setDataValue(charPressDish.from.day+'_dish_key_name',_this.oldValue);
        }else if(id == 'cancel'){
            this.params.stopEditing();
        }
    }

    updataAndStopEditing(name){
        this.currentValue = name;
        this.params.stopEditing();
    }

    updataActive(){
        let _this = this;
        // console.log('updataActive');
        this.el.querySelectorAll('li').forEach(function (e,i){
            if(i == _this.activeIndex){
                e.classList.add('active');
            }else{
                e.classList.remove('active');
            }
        });
    }

    updata_limit_category_id(){
        let _this = this;
    }

}


export default cellEditor
